/***************************************************************
*Copyright(c) 2020思特诺(Stduino)All right reserved.
*
*This library is open source and free for individual users. 
*
*For commercial use, please contact service001@stduino.com.
***************************************************************/

#include "StduinoPulse.h"

void analogWrite(uint8_t pin,uint16_t Value)
{
 *(uint32_t *)((uint32_t)_tim_grp(pin)+((_tim_prt(pin)-1)<<2)+0x34)=(Value);
 delayMicroseconds(1);
}

void tone(uint8_t pin,uint32_t hertz)
{
 uint32_t arr_add=2;
 uint32_t psc_add=1;
 uint32_t arr_data=0;
 uint32_t psc_data=0;
 uint16_t add_old=1000;
 uint16_t add_new=0;
 
 for(;arr_add<65536;arr_add+=2)
 {
  if(((72000000/(hertz*arr_add))<65536))
  {
   if((((72000000000/(hertz*arr_add))%1000))<10)
   {
    psc_add=(72000000/(hertz*arr_add));
    add_new=arr_add/psc_add+psc_add/arr_add;
    if(add_new<add_old||add_new<=200)
    {
     add_old=add_new;
     arr_data=arr_add;
     psc_data=psc_add;
    }
   }
  }
 }
 
 _tim_grp(pin)->ARR=arr_data-1;
 _tim_grp(pin)->PSC=psc_data-1;
 analogWrite(pin,(arr_data/2));
}

void noTone(uint8_t pin)
{
 settim(pin);
 analogWrite(pin,0);
}

uint32_t pulseIn(uint8_t pin,uint8_t state,uint32_t time)
{
 uint32_t time_start=micros();
START:
 if(digitalRead(pin)!=state)
 {
  while(1)
  {
   if(digitalRead(pin)==state)
   {
    uint32_t state_start=micros();

    while(1)
    {
     uint32_t time_now=micros()+1;
     if(digitalRead(pin)!=state)
     {
      return (time_now-state_start);
     }

     if((time_now-time_start)>=time)
     {
      return (time_now-state_start);
     }
    }
   }else
   {
    if((micros()-time_start)>=time)
    {
     return 0;
    }
   }
  }
 }
 else 
 {
  goto START;
  return 0;
 }
}

uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder)
{
 uint8_t value = 0;
 uint8_t i;
 
 for (i = 0; i < 8; ++i)
 {
  digitalWrite(clockPin, HIGH);
  
  if (bitOrder == 0)
  {
   value |= digitalRead(dataPin) << i;
  }else
  {
   value |= digitalRead(dataPin) << (7 - i);
  }
  digitalWrite(clockPin, LOW);
 }
  
 return value;
}

void shiftOut(uint8_t dataPin,uint8_t clockPin,uint8_t bitOrder,uint8_t val)
{
 uint8_t i;
 
 for (i = 0; i < 8; i++)
 {
  if (bitOrder == 0)
  {
   digitalWrite(dataPin, !!(val & (1 << i)));
  }else	
  {
   digitalWrite(dataPin, !!(val & (1 << (7 - i))));
  }

  digitalWrite(clockPin, HIGH);
  digitalWrite(clockPin, LOW);		
 }
}

/***************************************************************
*Copyright(c) 2020思特诺(Stduino)All right reserved.
*
*This library is open source and free for individual users. 
*
*For commercial use, please contact service001@stduino.com.
***************************************************************/
